package com.shuhe.domain.mxgc;

import com.shuhe.common.Tools;
import com.shuhe.domain.dbTodb.DbToDb;
import com.shuhe.metastore.MetaMysql;
import org.apache.log4j.Logger;

import java.sql.Connection;
import java.sql.ResultSet;
import java.util.*;

import static com.shuhe.common.CommonFunction.closeDb;
import static com.shuhe.common.Tools.dateFormat;
import static com.shuhe.common.Tools.getConnect;
import static com.shuhe.handler.DataInHandler.getMxUserSjjrTaskResponseBodys;
import static com.shuhe.handler.DataInHandler.getSjy;

public class TaskCron {
    private static Logger logger = Logger.getLogger(TaskCron.class);
    public static Properties globalProperties = new Properties();
    public static String batchId = "";

    public TaskCron() {
        String cTime = dateFormat(new Date());  //当前时间
        batchId = UUID.randomUUID().toString().replace("-", "");
        Connection metaConn = null;
        try {
            metaConn = MetaMysql.connect();
            logger.info("----------------" + "定时任务开始，本次开始时间'" + cTime + "'----------------");
            String sql = "SELECT id,datasource_id,table_name,task_name,task_status,run_cron,cron_type," +
                    "timeadd_column,timecolumn_format,start_time,new_time,modify_time,desttable_name,task_type," +
                    "user_name,timeadd_interval,no_task_time_begin,no_task_time_end FROM mxgc_user_task_sjjr a " +
                    "where task_status='run' and exists " +
                    " (select  1   from mxgc_user_sjygl b where b.id=a.datasource_id)  ";
            ArrayList<MxUserSjjrTaskResponseBody> mxUserSjjrTaskResponseBodys;
            mxUserSjjrTaskResponseBodys = getMxUserSjjrTaskResponseBodys(metaConn, sql);
            //整体日志开始
            sql = "insert into klj_rwxx_xq(plrwmc,plrwid,rwmc,rwfl,zxzt,zxqsrq,zxzzrq,sjl,updatetime)\n" +
                    "values('接入任务','" + batchId + "','整体','数据接入','','" + dateFormat(new Date()) + "','','','"
                    + dateFormat(new Date()) + "')";
            MetaMysql.execSql(metaConn, sql);
            if (mxUserSjjrTaskResponseBodys.size() > 0) {
                //1。1接入任务
                DbToDb.execute(mxUserSjjrTaskResponseBodys.get(0), "auto", batchId);
            }

            //1.2模型任务
            //bz  ""全量, 有值代表表名前3位
            new TaskMxgc("", batchId, cTime);

            //1.4推送接口
            ArrayList<PushApiConfig> pushApiConfigs = new ArrayList<>();
            sql = "SELECT a.id service_id,a.task_name service_name,a.id service_code,d.db_name api_server_addr," +
                    "b.api_head,a.user_name,b.token_method,b.token_addr,a.table_name full_table_name " +
                    "FROM mxgc_user_task_sjjr a,push_platform_config b,mxgc_user_sjygl d WHERE a.id=b.id " +
                    "AND a.datasource_id=d.id AND a.task_type='push' AND a.task_status='run' AND EXISTS (\n" +
                    "SELECT 1 FROM pz_run_task_server_ts_pc g WHERE g.task_id=a.id)";

            pushApiConfigs = getPushApiConfigs(metaConn, sql);
            if (pushApiConfigs.size() > 0) {
                for (int i = 0; i < pushApiConfigs.size(); i++) {
                    HttpPush httpPush = new HttpPush();
                    if (pushApiConfigs.get(i).getPlatformCode().equals("json_001")) {
                        httpPush.HttpPush(pushApiConfigs);
                    } else if (pushApiConfigs.get(i).getPlatformCode().equals("json_002")) {
                        httpPush.httpPush2(pushApiConfigs);  //待修改
                    } else {
                    }
                }
            }
            //整体日志结束
            sql = "update klj_rwxx_xq a set a.zxzzrq='" + dateFormat(new Date()) + "',a.updatetime='"
                    + dateFormat(new Date()) + "' where a.plrwid='" + batchId + "' and a.rwmc like'%整体%'";
            MetaMysql.execSql(metaConn, sql);
            logger.info("----------------" + "定时任务结束，本次开始时间" + dateFormat(new Date())
                    + "----------------");
            //休眠设置
            Thread.sleep(1000);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            closeDb(metaConn);
        }
    }

    public static ArrayList<PushApiConfig> getPushApiConfigs(Connection metaConn, String sql) throws Exception {
        ArrayList<PushApiConfig> pushApiConfigs = new ArrayList<>();
        try {
            ResultSet rs = MetaMysql.querySql(metaConn, sql);
            while (rs.next()) {
                PushApiConfig pushApiConfig = new PushApiConfig();
                pushApiConfig.setServiceId(rs.getString("service_id"));
                pushApiConfig.setServiceCode(rs.getString("service_code"));
                pushApiConfig.setServiceName(rs.getString("service_name"));
                pushApiConfig.setApiServerAddr(rs.getString("api_server_addr"));
                pushApiConfig.setApiHead(rs.getString("api_head"));
                pushApiConfig.setUserName(rs.getString("user_name"));
                pushApiConfig.setTokenMethod(rs.getString("token_method"));
                pushApiConfig.setTokenAddr(rs.getString("token_addr"));
                pushApiConfig.setFullTableName(rs.getString("full_table_name"));
                pushApiConfig.setPlatformCode(rs.getString("platform_code"));
                pushApiConfigs.add(pushApiConfig);
            }
            return pushApiConfigs;
        } finally {
        }
    }

}
